package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * sky-take-out
 * com.sky.controller.admin
 *
 * @author Ablecisi
 * @version 1.0
 * 2025/2/28
 * 星期五
 * 23:59
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    private final AliOssUtil aliOssUtil; // 阿里云OSS工具类

    @Autowired
    public CommonController(AliOssUtil aliOssUtil) {
        this.aliOssUtil = aliOssUtil;
    }

    @RequestMapping("/upload")
    @ApiOperation("上传文件")
    public Result<String> upload(MultipartFile file) {
        log.info("上传文件");

        try {
            String originalFilename = file.getOriginalFilename(); // 获取文件名
            if (originalFilename == null) { // 文件名为空
                return Result.error(MessageConstant.UPLOAD_FAILED); // 上传失败
            }
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".")); // 获取文件后缀
            String uuid = UUID.randomUUID() + extension; // 生成唯一文件名

            String url = aliOssUtil.upload(file.getBytes(), uuid); // 上传文件
            return Result.success(MessageConstant.UPLOAD_SUCCESS, url); // 上传成功
        } catch (Exception e) {
            throw new RuntimeException(e); // 抛出异常
        }
    }
}
